# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import re
import os
import redis
from django.shortcuts import render,HttpResponse
from app_sys import models
from app_cmdb.models import HostInfo,HostGroup
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from app_auth.views import Perms_required
from app_sys import salt_script,get_dir
from mtrops.settings import BASE_DIR,REDIS_HOST,HOST




@login_required
@Perms_required
def Depend(request):
    title = '环境部署'

    hostgroup_obj = HostGroup.objects.all()
    tree_info = []
    n=1
    for i in hostgroup_obj:
        hostgroup_id = i.id
        hostgroup_name = i.group_name
        hostinfo_obj = HostInfo.objects.filter(host_group_id=hostgroup_id)
        if n == 1:
            tree_info.append({"id": hostgroup_id, "pId": 0, "name": hostgroup_name, "open": "true"})
        else:
            tree_info.append({"id": hostgroup_id, "pId": 0, "name": hostgroup_name, "open": "false"})
        n+=1
        for j in hostinfo_obj:
            host_id = j.id
            host_ip = j.IP
            id = hostgroup_id * 10 + host_id
            if j.os_type == "Linux":
                tree_info.append({"id": id, "pId": hostgroup_id, "name": host_ip})
            else:
                pass
    data = json.dumps(tree_info, ensure_ascii=False)

    depend_obj = models.Server_Install.objects.all()
    depend_list = []
    for depend in depend_obj:
        depend_id = depend.id
        depend_name = depend.depend_name
        depend_version = depend.depend_version

        install_script = depend.install_script
        depend_list.append({'depend_id':depend_id,'depend_name':depend_name,'depend_version':depend_version,'install_script':install_script})
    return render(request, "sys_server.html", locals())





@csrf_exempt
@login_required
@Perms_required
def AddDepend(request):
    if request.method == 'POST':
        depend_name = request.POST.get('depend_name')
        depend_version = request.POST.get('depend_version')

        install_script = request.POST.get('install_script')

        try:
            depend_obj = models.Server_Install(depend_name=depend_name, depend_version=depend_version,install_script=install_script)
            depend_obj.save()
            return HttpResponse('添加成功')
        except:
            return HttpResponse('添加失败')
    else:
        return HttpResponse("未知请求")



@csrf_exempt
@login_required
@Perms_required
def EditDepend(request):
    if request.method == "POST":
        depend_id = request.POST.get("depend_id")
        depend_name = request.POST.get('depend_name')
        depend_version = request.POST.get('depend_version')


        install_script = request.POST.get('install_script')
        action = request.POST.get("action", None)
        if action:
            depend_obj = models.Server_Install.objects.get(id=depend_id)
            depend_obj.depend_name = depend_name
            depend_obj.depend_version = depend_version


            depend_obj.install_script = install_script
            depend_obj.save()
            return HttpResponse("修改成功")
        else:
            depend_info = models.Server_Install.objects.get(id=depend_id)
            info_json = {'depend_id':depend_info.id,'depend_name':depend_info.depend_name,'depend_version':depend_info.depend_version,'install_script':depend_info.install_script}
            info_json = json.dumps(info_json)
            return HttpResponse(info_json)
    else:
        return HttpResponse("未知请求")



@csrf_exempt
@login_required
@Perms_required
def DelDepend(request):
    if request.method == "POST":
        depend_id = request.POST.get("depend_id")
        models.Server_Install.objects.get(id=depend_id).delete()
        return HttpResponse("已删除")


@csrf_exempt
@login_required
@Perms_required
def Install(request):

    if request.method == "POST":
        depend_id = request.POST.get("depend_id")
        ip_json = request.POST.get("node_id_json")

        ip_list = []
        for i in json.loads(ip_json):
            if re.search("\d+.\d+.\d+.\d",i):
                ip_list.append(i)
        depend_obj = models.Server_Install.objects.get(id=depend_id)
        install_script = depend_obj.install_script
        depend_name = depend_obj.depend_name


        script_name = "install_%s" % depend_name

        script_file = os.path.join(BASE_DIR, 'static', 'scripts',script_name)

        f = open(script_file,'wb')

        f.write(install_script)

        f.close()

        script_file = "salt://%s" % script_file

        result = salt_script.Install(ip_list,script_file)

        return HttpResponse(result)




@csrf_exempt
@login_required
@Perms_required
def FileMG(request,ip=HOST,Dir=None):


    title = "文件管理"

    r = redis.Redis(host=REDIS_HOST, port=6379, db=0)

    print Dir

    hostgroup_obj = HostGroup.objects.all()
    tree_info = []

    for i in hostgroup_obj:
        hostgroup_id = i.id
        hostgroup_name = i.group_name
        hostinfo_obj = HostInfo.objects.filter(host_group_id=hostgroup_id)
        tree_info.append({"id":hostgroup_id, "pId":0, "name":hostgroup_name, "open":"true"})

        for j in hostinfo_obj:
            host_id = j.id
            host_ip =  j.IP
            id = hostgroup_id*10+host_id

            if j.os_type=="Windows":
                pass
            else:
                tree_info.append({"id": id, "pId": hostgroup_id, "name": host_ip})

    data =  json.dumps(tree_info,ensure_ascii=False)


    if Dir:
        cd_dir = r.get('cur_dir')+Dir
    else:
        cd_dir = '/'


    a = get_dir.main(ip,cd_dir)


    #a={'192.168.1.218': '/\ndr-xr-xr-x .\ndr-xr-xr-x ..\n-rw-r--r-- .autofsck\n-rw-r--r-- .autorelabel\ndr-xr-xr-x bin\ndr-xr-xr-x boot\ndrwxr-xr-x cgroup\ndrwxr-xr-x codeRelease\ndrwxr-xr-x dev\ndrwxr-xr-x etc\ndrwxr-xr-x gogs\ndrwxr-xr-x gogs-repositories\ndrwxr-xr-x home\ndr-xr-xr-x lib\ndr-xr-xr-x lib64\ndrwx------ lost+found\ndrwxr-xr-x media\ndrwxr-xr-x misc\ndrwxr-xr-x mnt\ndrwxr-xr-x net\n-rw------- nohup.out\ndrwxr-xr-x opt\ndr-xr-xr-x proc\ndr-xr-x--- root\ndrwxr-xr-x salt-push\ndr-xr-xr-x sbin\ndrwxr-xr-x selinux\ndrwxr-xr-x siteDir\ndrwxr-xr-x srv\ndrwxr-xr-x sys\ndrwxrwxrwt tmp\ndrwxr-xr-x usr\ndrwxr-xr-x var'}



    cur_dir =  a[ip].split("\n")[0]


    r.set('cur_dir', cur_dir)

    r.set('cur_host', ip)

    file_list = []

    dir_list = []

    for i in a[ip].split("\n")[1:]:
        F = i.split()
        if re.match(r"-", F[0]):
            file_list.append(F[1])

        else:
            dir_list.append(F[1])


    info=json.loads(r.get("webssh_info"))

    return render(request,"sys_file.html",locals())
